import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import verifyToken from '@/middlewares/verifyToken'
import { Models } from '@/common/typings/modle'
import { Success } from '@/core/HttpException'
import { command } from '@/server/mysql'
import { getStatusCondition } from '@/common/utils/sql'
import { isAdmin } from '@/api/v1/system/role/isAdmin'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/role`,
})
router.post('/list', verifyToken, async (ctx: Models.Ctx) => {
  // 此接口，如果不传 status 则查询全部数据
  const { status } = ctx.request.body as any
  const ia = await isAdmin(ctx)
  console.log('ctx.auth', ctx.auth)
  const { finallyResult } = await getRoleList({
    ...(ctx.request.body as any),
    ...(status === undefined ? { status: '' } : {}),
    ia,
  })

  throw new Success({
    data: finallyResult,
    total: finallyResult.length,
  })
})
export default router

/**
 * 此方法若不传status 则查询启用的
 */
export async function getRoleList({ roleName, roleCode, resourceList, userList, status = '1', ia }: any) {
  // 根据orderField 和 orderDirection 进行排序
  let realResult: any[] = []
  let sqlWhere = ''
  sqlWhere += `${roleName ? ` AND r.role_name LIKE '%${roleName}%'` : ``}`
  sqlWhere += `${roleCode ? ` AND r.role_code LIKE '%${roleCode}%'` : ``}`
  sqlWhere += getStatusCondition(status, true, 'r')
  if (!ia) {
    sqlWhere += ` AND r.role_code <> 'admin'`
  }
  sqlWhere = sqlWhere.replace(' AND', '')
  const result: any = (
    await command(
      `SELECT r.id, r.role_code, r.role_name, r.status, u.user_name, u.id as user_id, re.label, re.id as resource_id, re.unique_prop FROM system_role r
      JOIN system_role_resource rr ON r.id = rr.role_id
      JOIN system_resource re ON re.id = rr.resource_id
      JOIN system_user_role ur ON ur.role_id = r.id
      JOIN system_user u ON u.id = ur.user_id ${sqlWhere ? `WHERE ${sqlWhere}` : ''};`,
      true,
    )
  ).results
  result.forEach((item: any) => {
    const roleItem = realResult.find((r: any) => r.id === item.id)
    if (roleItem) {
      const resourceItem = roleItem.resourceList.find((r: any) => r.id === item.resourceId)
      if (!resourceItem) {
        roleItem.resourceList.push({
          id: item.resourceId,
          name: item.label,
          uniqueProp: item.uniqueProp,
        })
      }
      const userItem = roleItem.userList.find((r: any) => r.id === item.userId)
      if (!userItem) {
        roleItem.userList.push({
          id: item.userId,
          name: item.userName,
        })
      }
    } else {
      realResult.push({
        id: item.id,
        roleCode: item.roleCode,
        roleName: item.roleName,
        status: item.status,
        resourceList: [
          {
            id: item.resourceId,
            name: item.label,
            uniqueProp: item.uniqueProp,
          },
        ],
        userList: [
          {
            id: item.userId,
            name: item.userName,
          },
        ],
      })
    }
  })

  let finallyResult = []
  if ((resourceList && resourceList.length) || (userList && userList.length)) {
    realResult.forEach((item) => {
      let rFlag = false
      if (resourceList && resourceList.length) {
        if (resourceList.every((rId: any) => item.resourceList.some((rItem: any) => rItem.id === rId))) {
          // 满足resourceList 条件
          rFlag = true
        }
      } else {
        rFlag = true
      }
      let uFlag = false
      if (userList && userList.length) {
        if (userList.every((uId: any) => item.userList.some((uItem: any) => uItem.id === uId))) {
          // 满足userList 条件
          uFlag = true
        }
      } else {
        uFlag = true
      }
      if (rFlag && uFlag) {
        finallyResult.push(item)
      }
    })
  } else {
    finallyResult = realResult
  }
  return { finallyResult }
}
